package storage

import (
	"github.com/NetEase-Object-Storage/nos-golang-sdk/config"
	"github.com/NetEase-Object-Storage/nos-golang-sdk/logger"
	"github.com/NetEase-Object-Storage/nos-golang-sdk/nosclient"
	"github.com/NetEase-Object-Storage/nos-golang-sdk/model"
	"strings"
	"fmt"
	"os"
	"io"
	"errors"
	"layim/helper"
)

var nos_endpoint = "nos-eastchina1.126.net"
var nos_access_key = "ba46ff645f6a476b9ecf13e31b426277"
var nos_secret_key = "eb6368e1cc0143ad915a6b2c80864e20"
var nos_bucket = "iris-layim"

type Nos struct {
	client *nosclient.NosClient
}

func (nos *Nos) getInstance() *nosclient.NosClient {
	if nos.client != nil {
		return nos.client
	}
	conf := &config.Config{
		Endpoint:                    nos_endpoint,
		AccessKey:                   nos_access_key,
		SecretKey:                   nos_secret_key,
		NosServiceConnectTimeout:    3,
		NosServiceReadWriteTimeout:  15,
		NosServiceMaxIdleConnection: 500,
		LogLevel:                    logger.LogLevel(logger.DEBUG),
		Logger:                      logger.NewDefaultLogger(),
	}
	nosClient, err := nosclient.New(conf)
	if err != nil {
		panic(err)
	} else {
		nos.client = nosClient
		return nosClient
	}
}

//上传文件
func (nos *Nos) UploadFile(filePath string) (path string, err error) {
	exists, err := helper.FileExists(filePath)
	if err != nil {
		return "", err
	}
	if !exists {
		return "", errors.New("")
	}
	savePath := strings.Replace(filePath, "/", "-", 1)

	putObjectRequest := &model.PutObjectRequest{
		Bucket:   nos_bucket,
		Object:   savePath,
		FilePath: filePath,
	}
	_, err = nos.getInstance().PutObjectByFile(putObjectRequest)
	if err != nil {
		return "", err
	} else {
		url := "http://" + nos_bucket + "." + nos_endpoint + "/" + savePath
		return url, nil
	}
}

func (nos *Nos) DownloadFile(url string) (path string, err error) {
	objectRequest := &model.GetObjectRequest{
		Bucket: nos_bucket,
		Object: strings.Replace(url, "http://"+nos_bucket+"."+nos_endpoint+"/", "", 1),
	}
	fmt.Println("objectRequest", objectRequest)
	nosObj, err := nos.getInstance().GetObject(objectRequest)
	if err != nil {
		return "", err
	}
	downFile := "upload/" + string(helper.Krand(10, 3)) + ".jpg"
	file, err := os.Create(downFile)
	if err != nil {
		return "", err
	}
	defer file.Close()
	_, err = io.Copy(file, nosObj.Body)
	if err != nil {
		return "", err
	}
	return downFile, nil
}
